//	核心指标图

import React from 'react';
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import { WD_TYPE } from '../../EditorDataType/EnumConfig';
import { getComponentData } from 'src/services/AnalyseManage';
import { ChartService, IProps } from 'src/pages/AnalyseManage/EditReport/components/ChartsType/components/ChartService';
import { digitFormat, isNumber } from 'src/libs/utils';

interface ArrowType {
	num: number;
}

const ArrowComponent = ( props: ArrowType ) => {

	return props.num === 0 ? null : (
		props.num > 0 ? <ArrowUpOutlined style={ { color: '#86bc25' } }/> :
			<ArrowDownOutlined style={ { color: 'red' } }/> );
};

interface dataItem {
	label: string,
	count: number,
	YOY: number,				//	同比
	MOM: number				//	环比
}

export default class QuotaChart extends ChartService {

	state = {
		data: [
			{
				label: '销售额',
				count: 100,
				YOY: 80,				//	同比
				MOM: -20
			}
		],
		eventToken: [],
		dependencies: [],	//	图表联动参数
		isRender: false
	};

	style = () => {
		const { style } = this.props.config;
		return {
			display: 'flex',
			justifyContent: 'space-around',
			flexDirection: 'row' as 'row',
			height: style.titleShow === false ? '100%' : `calc(100% - ${ style.tilteHight || 0 }px)`,
			paddingBottom: `${ style.chartBottomPadding || 0 }px`,
			paddingLeft: `${ style.chartLeftPadding || 0 }px`,
			paddingRight: `${ style.chartRightPadding || 0}px`,
			paddingTop: `${ style.chartTopPadding || 0 }px`
		};
	};

	quotaItemStyle = {
		display: 'flex',
		flexDirection: 'column',
		justifyContent: 'center',
		flex: 1,
		overflow: 'hidden'
	} as React.CSSProperties;

	getLabelStyle = () => {
		let {
			labelFontFamily,
			labelFontSize,
			labelFontColor,
			labelFontBold,
			labelFontItalic,
			labelAlignHor
		} = this.props.config.style;
		return {
			fontFamily: labelFontFamily,
			fontSize: `${ labelFontSize || 15 }px`,
			color: labelFontColor,
			fontWeight: labelFontBold ? 'bold' : 'normal',
			fontStyle: labelFontItalic ? 'italic' : 'normal',
			textAlign: labelAlignHor ? labelAlignHor : 'center',
			width: '100%',
			height: '40px',
			paddingRight: 6,
			lineHeight: '40px',
			marginBottom: 0
		} as React.CSSProperties;
	};

	getValueStyle = () => {
		let {
			valueFontFamily,
			valueFontSize,
			valueFontColor,
			valueFontBold,
			valueFontItalic,
			valueAlignHor
		} = this.props.config.style;
		return {
			fontFamily: valueFontFamily,
			fontSize: `${ valueFontSize || 15 }px`,
			color: valueFontColor,
			fontWeight: valueFontBold ? 'bold' : 'normal',
			fontStyle: valueFontItalic ? 'italic' : 'normal',
			textAlign: valueAlignHor ? valueAlignHor : 'center',
			width: '100%',
			height: '40px',
			lineHeight: '40px',
			marginBottom: 0
		} as React.CSSProperties;
	};

	getQOQStyle = () => {
		let {
			QOQLabelFontFamily,
			QOQLabelFontSize,
			QOQLabelFontColor,
			QOQLabelFontBold,
			QOQLabelFontItalic,
			QOQLabelAlignHor
		} = this.props.config.style;
		return {
			fontFamily: QOQLabelFontFamily,
			fontSize: `${ QOQLabelFontSize || 15 }px`,
			color: QOQLabelFontColor,
			fontWeight: QOQLabelFontBold ? 'bold' : 'normal',
			fontStyle: QOQLabelFontItalic ? 'italic' : 'normal',
			textAlign: QOQLabelAlignHor ? QOQLabelAlignHor : 'center',
			width: '100%',
			marginBottom: 0
		} as React.CSSProperties;
	};

	getAlignStyle = () => {

		return {
			width: '50%',
			display: 'inline-flex',
			justifyContent: 'space-evenly',
			flexWrap: 'wrap'
		} as React.CSSProperties;

	};


	getQOQValueStyle = () => {
		let {
			QOQLabelFontFamily,
			QOQValueFontSize,
			QOQValueFontColor,
			QOQValueFontBold,
			QOQValueFontItalic,
			QOQValueAlignHor
		} = this.props.config.style;
		return {
			fontFamily: QOQLabelFontFamily,
			fontSize: `${ QOQValueFontSize || 15 }px`,
			color: QOQValueFontColor,
			fontWeight: QOQValueFontBold ? 'bold' : 'normal',
			fontStyle: QOQValueFontItalic ? 'italic' : 'normal',
			textAlign: QOQValueAlignHor ? QOQValueAlignHor : 'center',
			width: '100%'
		} as React.CSSProperties;
	};

	async getConditionData() {
		let { config } = this.props;

		//	如果度量字段为空，则不请求数据
		if ( !config.data.coreKey || config.data.coreKey.length === 0 ) return;

		//	如果开启了同比或环比，且没有拖入日期字段，则不请求数据
		if (
			( config.data.isYOYAvailable === true || config.data.isMOMAvailable === true ) &&
			( !config.data.coreDate || config.data.coreDate.length === 0 )
		) return;


		const x = config.data.coreKey.map( v => {
			return {
				aggregateType: v.aggregateType,	//	度量的聚合类型
				formatType: '',	// 维度的聚合类型
				alias: v.title,
				dataType: v.dataType,
				frontendId: '',
				id: v.name,
				orderType: v.orderType,	//	排序方式
				quota: v.modelType === WD_TYPE ? 'WD' : 'DL',
				symbol: '',
				type: v.type,
				value: '',
				dataUnit: v.dataUnit,
				precision: v.precision,
			};
		} );
		const dateFields = config.data.coreDate && config.data.coreDate.map( v => {
			return {
				coreYoy: config.data.isYOYAvailable === true ? true : false,				// 是否开启同比
				coreChain: config.data.isMOMAvailable === true ? true : false,			// 是否开启环比
				coreDateValue: `${ new Date().getFullYear() }-${ new Date().getMonth() * 1 + 1 }-${ new Date().getDate() }`,
				coreDateKey: v.name,
				coreDateType: v.formatType
			};
		} );
		// const conditions = this.props.config.data.filterFields ? this.props.config.data.filterFields.map( v => v.filterConditions ).flat() : [];
		// 内部筛选 condition
		const filterFieldCondition = this.props.config.data.filterFields
			? this.props.config.data.filterFields.map( ( v ) => v.filterConditions ).flat()
			: [];

		// 筛选组件的 condition
		let filterCompConditions = this.props.config.data.filterConditions || {};
		let newFilterCompConditions = [];
		Object.keys( filterCompConditions ).forEach( ( key ) => {
			newFilterCompConditions = newFilterCompConditions.concat( filterCompConditions[ key ] );
		} );

		const request: any = {

			dataConfig: {
				dataModel: {
					pageId: this.props.pageId,
					tableName: config.data.tableCode,
					x: x,
					conditions: filterFieldCondition.concat( this.state.dependencies, newFilterCompConditions )
					// customParams: {}
				},
				needAutoRefresh: true,
				tableType: 'core'
			},
			type: 'quota',
			tenantCode: this.props.tenantCode
		};

		if ( dateFields ) {
			request.dataConfig.dataModel.customParams = dateFields[ 0 ];
		}

		let pageResponse = await getComponentData( request );
		if ( pageResponse.data && pageResponse.data.success && pageResponse.data.data.rows && pageResponse.data.data.rows.length > 0 ) {
			let info = pageResponse.data.data.rows;
			const data = info.map( v => {
				return {
					YOY: v.yoy,
					MOM: v.chain,
					count: v.value,
					label: v.name,
					precision: v.precision || '',
					dataUnit: v.dataUnit || ''
				};
			} );
			this.setState( {
				data: data
			} );
		}
	}

	//	拖拽字段后，设置区块颜色
	setCustomColor = () => {
		const oldCustomBlockColor = this.props.config.style.customBlockColor;
		const customBlockColor = this.state.data.map( v => {
			const item = oldCustomBlockColor.find( i => i.item === v.label );
			return {
				color: item ? item.color : '#fff',
				item: v.label
			};
		} );

		this.props.onValuesChange && this.props.onValuesChange( 'Quota', this.props.id, {
			customBlockColor: customBlockColor
		}, 'style' );
	};

	//	初始化设置自定义区块颜色
	initCustomColor = () => {
		const customBlockColor = this.state.data.map( v => {
			return {
				color: '#fff',
				item: v.label
			};
		} );

		this.props.onValuesChange && this.props.onValuesChange( 'Quota', this.props.id, {
			customBlockColor: customBlockColor
		}, 'style' );
	}

	getBlockColor = ( label ) => {
		let color = '#fff';
		if ( this.props.config.style.customBlockColor ) {
			let item = this.props.config.style.customBlockColor.find( v => v.item === label );
			if ( item ) color = item.color;
		}

		return Object.assign( {}, this.quotaItemStyle, { backgroundColor: color } );

	}

	//	数字格式化
	numFormat = ( data, num ) => {

		let { precision = '', dataUnit = '', count } = data;
		count = isNumber( precision ) ? count.toFixed( precision ) : count;
		count = digitFormat( count, num );
		return `${ count }${ dataUnit }`;
	};

	shouldComponentUpdate( nextProps: Readonly<IProps>, nextState: Readonly<{}>, nextContext: any ): boolean {
		if ( JSON.stringify( nextProps ) !== JSON.stringify( this.props ) || JSON.stringify( nextState ) !== JSON.stringify( this.state ) ) return true;
		return false;
	}

	getSnapshotBeforeUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{ dependencies: any }> ): any | null {
		let { config } = this.props;
		let changeObj = Object.create( null );
		if ( JSON.stringify( prevProps.config.data ) !== JSON.stringify( config.data ) ||
			JSON.stringify( this.state.dependencies ) !== JSON.stringify( prevState.dependencies ) ) {
			changeObj.needDataChange = true;
		}
		return changeObj;
	}

	async componentDidUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{}>, snapshot?: any ) {

		if ( snapshot.needDataChange ) {
			await this.getConditionData();
		}

		if ( !this.props.config.style.customBlockColor ) {
			return this.initCustomColor();
		} else if ( snapshot.needDataChange ) {
			this.setCustomColor();
		}
	}

	initEvent = async () => {
		this.getConditionData();
		this.setState( { isRender: true } );
	};

	render() {
		let { data, style } = this.props.config;
		return (
			<div id={ this.props.id } style={ this.style() }>
				{
					this.state.data.map( ( dataItem: any, index ) => {
						return (
							<div key={ index } style={ this.getBlockColor( dataItem.label ) }>
								<p style={ this.getValueStyle() }>
									{/*百分比指标*/ }
									{
										data.quotaType === 'percent' && `${ ( dataItem.count * 100 ).toFixed( dataItem.precision || 0 ) }%`
									}
									{/*核心指标*/ }
									{
										data.quotaType !== 'percent' && (
											this.numFormat( dataItem, style.valueSplitStyle === 'tenThousand' ? 4 : 3 )

										)
									}

									{
										style.valueUnitVisible && style.valueUnit
									}
								</p>
								{
									style.isShowLabel !== false &&
                  <p style={ this.getLabelStyle() }>{ style.labelValue || dataItem.label }</p>
								}
								{
									( data.isYOYAvailable === true || data.isMOMAvailable === true ) && (
										<div style={ this.getQOQStyle() }>
											<p style={ this.getAlignStyle() }>
												{
													data.isYOYAvailable === true && (
														<span style={ { 'whiteSpace': 'nowrap' } }>同比
															<i style={ this.getQOQValueStyle() }>{ `${ dataItem.YOY || 0 }%` }</i>
															{ style.isShowArrow !== false &&
															<ArrowComponent num={ dataItem.YOY }></ArrowComponent> }
														</span>
													)
												}

												{
													data.isMOMAvailable === true && (
														<span style={ { 'whiteSpace': 'nowrap' } }>环比
															<i style={ this.getQOQValueStyle() }>{ `${ dataItem.MOM || 0 }%` }</i>
															{ style.isShowArrow !== false &&
															<ArrowComponent num={ dataItem.MOM }></ArrowComponent> }
														</span>
													)
												}
											</p>


										</div>
									)
								}

							</div>
						);
					} )
				}

			</div>
		);
	}
}
